﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Threading;

namespace ExcelControlManager
{
    public partial class MainForm : Form
    {
        string strFolderPath = "";
        static int nFilesCount = 0;
        List<FileInfo> TargetFiles;
        
        public MainForm()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                nFilesCount = 0;
                strFolderPath = folderBrowserDialog1.SelectedPath;
                FileNameTextBox.Text = strFolderPath;
                int FilesCount = GetFiles(new DirectoryInfo(@strFolderPath),"*.xlsx");
                if(FilesCount >= 0)
                    label2.Text = "共检索到：" + FilesCount.ToString() + "个文件，请输入检索关键字：";
            }
            else
                MessageBox.Show("未选择文件夹，请重新选择", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        public int GetFiles(DirectoryInfo directory, string pattern)
        {
            try
            {
                if (directory.Exists || pattern.Trim() != string.Empty)
                {
                    TargetFiles = new List<FileInfo>();
                    foreach (FileInfo info in directory.GetFiles(pattern))
                    {
                        TargetFiles.Add(info);
                        nFilesCount++;
                    }
                    foreach (DirectoryInfo info in directory.GetDirectories())
                    {
                        GetFiles(info, pattern);
                    }
                    return nFilesCount;
                }
                else
                    return 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return -1;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            StartShowOutputInfoFormThread();
        }

        private void StartShowOutputInfoFormThread()
        {
            Thread thdOutputInfoForm = new Thread(ShowOutputInfoForm);
            thdOutputInfoForm.IsBackground = true;
            thdOutputInfoForm.Start();
        }

        private void ShowOutputInfoForm()
        {
            if (this.KeyWordTextBox.Text != "")
            {
                OutputInfoForm outputinfoForm = new OutputInfoForm(TargetFiles, this.KeyWordTextBox.Text);
                outputinfoForm.ShowDialog();
            }
            else
                MessageBox.Show("没有指定关键字，请指定关键词", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
    }
}
